/*
 * Copyright 2013-2018 Lilinfeng.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package main.java.com.waylau.netty.demo.privateprotocol.server;

import com.alibaba.fastjson.JSON;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import main.java.com.waylau.netty.demo.privateprotocol.struct.Header;
import main.java.com.waylau.netty.demo.privateprotocol.struct.NettyMessage;
import main.java.com.waylau.netty.demo.privateprotocol.util.MessageType;

/**
 * @author Lilinfeng
 * @date 2014年3月15日
 * @version 1.0
 */
@ChannelHandler.Sharable
public class ChatHandler extends SimpleChannelInboundHandler<Object> {
	/**
	 * 当有新的连接请求
	 * @param ctx
	 * @throws Exception
	 */
	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
		System.out.println(this.getClass().getSimpleName() + ":channelRegistered");
	}

	/**
	 * 服务器接收到来自客户端的请求
	 */
	@Override
	public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println(this.getClass().getSimpleName() + "收到消息");
		//因为这里全部都转成字符串了啊
		NettyMessage message = JSON.parseObject((String) msg, NettyMessage.class);
		if (message.getHeader()!=null&&message.getHeader().getType()==MessageType.SERVICE_REQ.value()){
			// 回答一下客户端
			System.out.println("服务器接收到消息:"+message.getBody().toString());
//			ctx.writeAndFlush(JSON.toJSONString(buildResponse("我是服务器我接收到了你的请求")));
		}else {
			// 交给下一个Handler去处理
			ctx.fireChannelRead(msg);
		}
	}


	private NettyMessage buildResponse(String result) {
		NettyMessage message = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.SERVICE_RESP.value());
		message.setHeader(header);
		message.setBody(result);
		return message;
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
		ctx.fireExceptionCaught(cause);
	}
}
